package com.wangzh.nio.randomtest;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.把文件内容读取到内存中
        BufferedReader br = new BufferedReader(new FileReader("randomnames.txt"));
        ArrayList<Student> arrayList = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] split = line.split("-");
            Student student = new Student(split[0], split[1], Integer.parseInt(split[2]), Double.parseDouble(split[3]));
            arrayList.add(student);
        }
        br.close();


        //2.计算权重的总和
        double weight = 0;
        for (Student student : arrayList) {
            weight += student.getWeight();
        }

        //3.计算每一个人的占比
        double[] arr = new double[arrayList.size()];

        for (int i = 0; i < arrayList.size(); i++) {
            arr[i] = arrayList.get(i).getWeight() / weight;
        }

        //4.计算每一个人的权重占比范围
        // [0.1,0.2,0.3,0.4]
        for (int i = 1; i < arr.length; i++) {
            arr[i] = arr[i] + arr[i - 1];
        }

        //5.随机抽取
        double number = Math.random();
        //判断Number在arr中的位置  二分查找
        int index = -Arrays.binarySearch(arr, number) - 1;
        Student student = arrayList.get(index);

        //6.将权重减半，写入到文件
        BufferedWriter bf = new BufferedWriter(new FileWriter("randomnames.txt"));
        student.setWeight(student.getWeight()/2);
        for (Student student1 : arrayList) {
            bf.write(student1.toString1());
            bf.newLine();
        }
        bf.close();
        System.out.println(Arrays.toString(arr));
        System.out.println(student);

    }

}
